<script setup lang="ts">
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { onMounted, ref, onBeforeUnmount, watch } from 'vue'
const { text, options } = defineProps(['text', 'options'])
const emit = defineEmits(['update:value'])
const markdownBody = ref<HTMLElement | null>(null)
const editorInstance = ref<Vditor | null>(null)
onMounted(() => {
    editorInstance.value = new Vditor(
        markdownBody.value as HTMLElement, {
        ...options.value,
        cache: {
            enable: true,
            id: 'vditor-cache',
            type: 'local'
        },
        value: text.value,
        input: (val: string) => {
            emit('update:value', val)
            console.log(val)
        },
        after: () => {
            if (text.value) {
                editorInstance.value?.setValue(text.value)
            }
        },
        hint: {
            emoji: {
                url: 'https://cdn.jsdelivr.net/npm/vditor@3.8.7/dist/images/emoji/huaji.gif'
            }
        },
        upload : {
            handler : (files : File[]) => {
                return "[image](http://150.158.107.119:8080/assets/image/3953240110606292.png)"
            },
        }
    })
})
watch(() => text.value, (newVal) => {
    if (newVal !== editorInstance.value?.getValue()) {
        editorInstance.value?.setValue(newVal)
    }
    // console.log(newVal)
})

onBeforeUnmount(() => {
    editorInstance.value?.destroy()
    editorInstance.value = null
})
</script>

<template>
    <div ref="markdownBody" id="markdownBody"></div>
</template>